"""""""""""""""""""""""
""""""""主函数"""""""""
""""""""""""""""""""""""

import sys
import time
from Game import *

#初始化游戏并加载砖块
game=Game()
game.game_init()
game.load_level()

#创建按钮
play_button=Button(game.screen,"Play")
replay_button = Button(game.screen, "Play again?")

#实时监听
while True:

    #更新时钟，指定循环频率
    game.timer.tick(30)

    #获取自pygame.init（）调用以来的毫秒数
    ticks = pygame.time.get_ticks()

    #监听用户事件
    for event in pygame.event.get():
        # 判断用户是否点击了关闭按钮
        if event.type == QUIT:
            print("游戏退出...")
            pygame.quit()  # 卸载所有pygame模块
            exit()

        #键盘被放开
        if event.type == KEYUP:
            if cfg.game_active:
                if event.key == K_RETURN or len(game.block_group)==0:
                    game.goto_next_level()
                    game.load_ball()
                    game.reset_ball()

        #判断是否点击按钮
        if event.type==pygame.MOUSEBUTTONDOWN:
            mouse_x,mouse_y=pygame.mouse.get_pos()
            #点击play按钮
            if play_button.rect.collidepoint(mouse_x,mouse_y) and not cfg.game_active:
                cfg.game_active=True
            # 点击replay按钮
            if replay_button.rect.collidepoint(mouse_x,mouse_y) and cfg.game_over:
                cfg.game_active=True
                cfg.game_over=False
                cfg.score = 0
                cfg.lives = 3
                cfg.level = 0
                cfg.ball_num = 1
                game.game_init()
                game.load_level()

    #监测键盘
    keys = pygame.key.get_pressed()

    #退出游戏
    if keys[K_ESCAPE]:
        sys.exit()

    #用蓝色填充窗口
    game.screen.fill((50,50,100))

    # 游戏开始且未结束
    if cfg.game_active and not cfg.game_over:

        #游戏相关操作与检查碰撞
        game.update_blocks(ticks)
        game.move_paddle(keys,ticks)
        game.move_ball(ticks)
        game.collision_ball_paddle()
        game.collision_ball_blocks()

        #绘制精灵组
        game.block_group.draw(game.screen)
        game.ball_group.draw(game.screen)
        game.paddle_group.draw(game.screen)

        #打印相关数据
        print_text(game.font, 10, 0, "SCORE "+str(cfg.score))
        print_text(game.font, 170, 0, "LEVEL "+str(cfg.level+1))
        print_text(game.font, 320, 0, "BLOCKS "+str(len(game.block_group)))
        print_text(game.font, 490, 0, "lives "+str(cfg.lives))

    #绘制play按钮
    if not cfg.game_active:
        play_button.draw_button()
        print_text(game.font, 120, 360, "Tips:Reward a ball every 5 levels")
        print_text(game.font, 178, 390, "Reward a life every 10 levels")

    #游戏结束
    if cfg.game_over:
        print_text(game.font, 120, 380, "GAME OVER,YOU SCORE IS: "+str(cfg.score))
        replay_button.draw_button()

    #更新视图
    pygame.display.update()

    #线程睡眠
    time.sleep(1.0/60)